# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
use strict; use warnings;

package CCNCore::Provision::program_ser;
use base qw(CCNCore::Provision::Base);
use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;
use CCNv2::Provision::ser_parameters;


sub run()
{
    my $self = shift;
    return if $self->p->force_manager;

    $self->PACKAGE('openser');
    $self->PACKAGE('openser-mysql-module'); # At least on Debian..

    # Accounting location
    my $accounting_dir = '/var/log/openser';
    if($self->upgrading || ! -d $accounting_dir )
    {
        CCN::Scripting::exec_command(qq(mkdir -p "$accounting_dir" \&\& chown openser "$accounting_dir"));
    }

    # Should OpenSER be enabled?
    return $self->disable('openser') unless defined $self->p->{px_member};

    $self->enable('openser');

    # Generate ser.cfg
    
    my $SALT = $self->system_salt;

    my ($pxy_db_cluster,$dbname) = $self->sql_get(q(SELECT db_cluster, db_name FROM db_names WHERE pk = ).$self->p->{px_member});

    my @pxy_db_servers = $self->sql_get_array(q(SELECT pk FROM server WHERE db_member = ?),$pxy_db_cluster);
    return $self->error ("program_ser: has a database been selected for proxy cluster ".$self->p->{px_member}." ?")
        if $#pxy_db_servers < 0;

    # TBD Need better server selection algorithm.
    #     (Actually, need SER to support multiple database servers and failover.)
    my $pxy_db_server = $pxy_db_servers[0];
    $pxy_db_server = $self->p->server_pk
        if grep { $_ eq $self->p->server_pk } @pxy_db_servers;
    my $pxy_db_server_ip = $self->get_replication_ip_of($pxy_db_server);

    # See db_ser.pm
    my $password = $self->make_password(${pxy_db_cluster},${SALT},$self->p->server_pk,'ser');

    our %ser_values;

    $ser_values{PROXY_CLUSTER}      = $self->p->{px_member};
    # $ser_values{PROXY_IP} = server_intf_ip(${SERVER}, e "${SYSNAME}/server/${SERVER}/cluster/proxy/intf");
    $ser_values{PROXY_IP}           = $self->get_realtime_ip_of($self->p->server_pk);
    $ser_values{DB_URL}             = "mysql://ser:$password\@$pxy_db_server_ip/$dbname";
    $ser_values{DEFAULT_EXPIRE}     = 90;
    $ser_values{MIN_EXPIRE}         = 60;
    $ser_values{MAX_EXPIRE}         = 120; # in seconds; 0 = do not check
    $ser_values{CHALLENGE}          = $CCNv2::Provision::ser_parameters::USE_CHALLENGE;
    $ser_values{USE_DOMAIN_UL}      = $CCNv2::Provision::ser_parameters::USE_DOMAIN_UL;
    $ser_values{USE_DOMAIN_OTHER}   = 0;

    # my $client_short = $SERVER;
    # $client_short =~ s/\..*$//;
    # my $table = "domain_${client_short}";
    my $table = "domain";

    $ser_values{DOMAIN_TABLE} = $table;

    my $config = content_of(CCNCore::Home::manager.'/lib/templates/program_ser.txt');

    # Substitute ${variable} in the template ser.cfg code.
    $config =~ s/\$\{(\w+)\}/exists($ser_values{$1}) ? defined($ser_values{$1}) ? $ser_values{$1} : die("Undefined SER value $1 ") : die("Unexistent SER value $1")/ge;


    if( $self->p->operating_system =~ /debian|ccn/ )
    {
        foreach('/etc/default/openser')
        {
            CAT $_, <<'CONF';
RUN_OPENSER=yes
USER=openser
GROUP=openser
MEMORY=64
DUMP_CORE=no
CONF
            CCNv2::Scripting::IF_CHANGED_restart_openser($_);
        }
    }

    foreach('/etc/openser/openser.cfg')
    {
        CAT $_, $config;
        CCNv2::Scripting::IF_CHANGED_restart_openser($_);
    }
}

1;